package com.cb.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cb.eduservice.client.VodClient;
import com.cb.eduservice.entity.EduVideo;
import com.cb.eduservice.mapper.EduVideoMapper;
import com.cb.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cb.servicebase.exception.GuliException;
import com.cb.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author Cebb
 * @since 2020-06-22
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    private final VodClient vodClient;

    @Autowired
    public EduVideoServiceImpl(VodClient vodClient) {
        this.vodClient = vodClient;
    }

    @Override
    public void removeByCourseId(String courseId) {
        QueryWrapper<EduVideo> findVideoIdWrapper = new QueryWrapper<>();
        findVideoIdWrapper.select("video_source_id").eq("course_id", courseId);
        // 查询关联的视频id
        List<EduVideo> eduVideoList = baseMapper.selectList(findVideoIdWrapper);
        List<String> videoIds = new ArrayList<>(10);
        for (int i = 0; i < eduVideoList.size(); i++) {
            String videoId = eduVideoList.get(i).getVideoSourceId();
            if (!StringUtils.isEmpty(videoId)) {
                videoIds.add(videoId);
            }
        }
        if (videoIds.size() > 0) {
            // 通过feign调用vod模块方法 , 删除多个云端视频
            vodClient.removeBatchAliyunVideo(videoIds);
        }

        // 根据课程id , 删除小节信息
        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        baseMapper.delete(wrapper);
    }

    @Override
    public boolean removeByVideoId(String id) {
        //根据小节id先获取视频id
        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.select("video_source_id").eq("id", id);
        EduVideo eduVideo = baseMapper.selectOne(wrapper);
        String videoSourceId = eduVideo.getVideoSourceId();
        // 判断是否有视频id
        if (!StringUtils.isEmpty(videoSourceId)) {
            // 通过feign调用vod服务删除视频
            R result = vodClient.removeAliyunVideo(videoSourceId);
            // 可能触发熔断机制
            if (result.getCode() == 20001) {
                throw new GuliException(20001, "删除视频失败 , 请稍后重试....");
            }
        }
        // 删除小节信息
        int flag = baseMapper.deleteById(id);
        return flag > 0;
    }
}
